<template>
 <div class="conn-layout">
    <el-container>
      <el-header class="conn-button-container">
        <el-input v-model="connSearchKey" placeholder="搜索" :prefix-icon="Search" @input="handleSearch"/>
        <el-button-group>
          <el-button 
            type="default" 
            :icon="viewMode === 'table' ? Grid : List"
            @click="toggleViewMode"
            style="margin-right: 10px;"
          >
            {{ viewMode === 'table' ? '卡片视图' : '表格视图' }}
          </el-button>
          <el-button type="primary" :icon="Plus" @click="handleAddConn">新建数据连接</el-button>
        </el-button-group>
      </el-header>
      <el-main class="conn-table-container">
        <el-table v-if="viewMode === 'table'" :data="filteredTableData" stripe 
                  height="calc(100vh - 120px)" @row-click="handleRowClick">
          <el-table-column fixed prop="title" label="名称" />
          <el-table-column prop="options.type" label="类型" />
          <el-table-column prop="createdAt" label="创建时间" />
          <el-table-column prop="updatedAt" label="最近编辑" />
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button size="small" type="primary" plain :icon="Edit" @click="handleEdit(scope.$index, scope.row)" @click.stop>
              </el-button>
              <el-button size="small" type="danger" plain :icon="Delete" @click="handleDelete(scope.$index, scope.row)" @click.stop>
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div v-else class="card-container">
          <el-card v-for="item in filteredTableData" :key="item.id" class="conn-card" @click="handleRowClick(item)">
            <div class="card-content" @blur="closeDropdown">
              <el-dropdown class="card-more" trigger="click">
                <el-icon class="more-icon" @click.stop ><MoreFilled /></el-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleEdit(0, item)">
                      <el-icon><Edit /></el-icon>编辑
                    </el-dropdown-item>
                    <el-dropdown-item @click="handleDelete(0, item)">
                      <el-icon><Delete /></el-icon>删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>

              <div class="card-main">
                <div class="card-image-section">
                  <img :src="logoMap[item.options.type.toLowerCase()]" class="card-logo" alt="database logo">
                </div>
                <div class="card-title-section">
                  <h3 class="card-title">{{ item.title }}</h3>
                </div>
              </div>

              <el-tooltip class="info-tooltip" effect="light" placement="right" :show-after="100" :hide-after="0">
                <template #content>
                  <div class="tooltip-content">
                    <p><span>类型：</span>{{ item.options.type }}</p>
                    <p><span>创建时间：</span>{{ item.createdAt }}</p>
                    <p><span>更新时间：</span>{{ item.updatedAt }}</p>
                  </div>
                </template>
                <el-icon class="info-icon">
                  <InfoFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </el-card>
        </div>
      </el-main>
    </el-container>

    <el-drawer v-model="showDrawer" :size="showDrawerSize" :with-header="false">
      <router-view v-slot="{ Component }">
        <transition name="slide-fade" mode="out-in" :style="{ '--slide-leave-dict': slideLeaveDict, '--slide-enter-dict': slideEnterDict }">
          <component :is="Component" @close="handDrawerClose" />
        </transition>
      </router-view>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, provide, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElButton, ElDrawer, ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Delete, Edit, Grid, List, MoreFilled, InfoFilled } from '@element-plus/icons-vue'
import { connectionList, connectionDelete } from '@/api/connection'
import type { Connection } from '@/types/api/connection'
import { logoMap } from '@/utils/logoLoader'

const showDrawer = ref(false)
const showDrawerSize = ref('70%')

const connSearchKey = ref('')
const slideEnterDict = ref(-1)    // 1 表示从右向左, -1 表示从左向右
const slideLeaveDict = ref(1)
const tableData = ref<Connection[]>([])
const viewMode = ref<'table' | 'card'>('card') // 默认卡片视图


// 提供更新方法给后代组件  TODO  页面切换方向没达到预期效果
provide('updateSlideDirection', (enter: number, leave: number) => {
  if (enter !== undefined) {
    slideEnterDict.value = enter
  }
  if (leave !== undefined) {
    slideLeaveDict.value = leave
  }
})


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 生命周期事件 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
onMounted(() => {
  fetchConnectionList()
})

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 计算属性相关 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// 根据搜索关键字过滤表格数据
const filteredTableData = computed(() => {
  if (!connSearchKey.value.trim()) return tableData.value
  return tableData.value.filter(item => 
    item.title.toLowerCase().includes(connSearchKey.value.toLowerCase().trim())
  )
})

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 组件事件 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// 页面搜索
const handleSearch = () => {
  connSearchKey.value =  connSearchKey.value.trim()
}

// 关闭抽屉的回调
const router = useRouter()
const handDrawerClose = () => {
  showDrawer.value = false
  router.push({ name: 'connection' })
  fetchConnectionList()
}

// 按钮【新增数据连接】事件：打开抽屉并导航到选择页面
const handleAddConn = () => {
  showDrawerSize.value = '70%'
  showDrawer.value = true
  router.push({ name: 'connSelection' })
}

// 按钮【删除】事件：删除数据连接
const handleDelete = (index: number, row: any) => {
  ElMessageBox.confirm( '确定删除？', '提示', {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', })
  .then(() => {
    connectionDelete(row.id).then(() => {
      fetchConnectionList()
    })
  })
}

// 按钮【编辑】事件：编辑数据连接  TODO 未实现
const handleEdit = (index: number, row: any) => {
  showDrawerSize.value = '70%'
  showDrawer.value = true
  router.push(
    {  
      name: 'connectionForm',
      query: {id: row.id, type: row.options.type, logo: logoMap[row.options.type.toLowerCase()], enterType: 'edit' }
    }
  )
}

// 处理行点击事件
const handleRowClick = (row: Connection) => {
  showDrawerSize.value = '100%'
  showDrawer.value = true
  router.push({
    name: 'dataPreview',
    params: { id: row.id }
  })
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Api 接口交互 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// 获取连接列表数据
const fetchConnectionList = async () => {
  const data = await connectionList({})
  tableData.value = data as any
}

// 添加切换视图的方法
const toggleViewMode = () => {
  viewMode.value = viewMode.value === 'table' ? 'card' : 'table'
}
</script>


<style scoped>

/* 顶部按钮容器样式 */
.conn-button-container {
  display: flex;                /* 使用弹性布局 */
  justify-content: flex-end;    /* 内容右对齐 */
  align-items: center;          /* 垂直居中对齐 */
  height: 40px;                 /* 固定容器高度 */
  margin: 5px 5px;             /* 上下外边距5px，左右无外边距 */
  padding: 0px 0px;            /* 无内边距 */
}

/* 表格容器样式 */
.conn-table-container {
  padding: 0;                   /* 无内边距 */
  margin-top: 2px;              /* 顶部外边距2px */
  margin-left: 5px;             /* 左边外边距5px */
  margin-right: 5px;            /* 右边外边距5px */
  height: calc(100vh - 120px);  /* 高度为视窗高度减去120px，确保表格不会溢出屏幕 */
}

/* 搜索输入框样式 */
.el-input {
  width: 240px;                /* 固定输入框宽度 */
  height: 35px;                /* 固定输入框高度 */
  margin-right: 5px;           /* 右侧外边距5px，与按钮组保持间距 */
}

/* 按钮组容器样式 */
.el-button-group {
  margin-right: 0px;           /* 右侧无外边距 */
}

/* 按钮样式 */
.el-button {
  height: 35px;                /* 固定按钮高度 */
  margin-right: 0px;           /* 右侧无外边距 */
}

/* 下拉菜单触发器样式（三个点的容器） */
.el-dropdown-link {
  cursor: pointer;             /* 鼠标悬停时显示手型光标 */
  display: flex;               /* 使用弹性布局 */
  align-items: center;         /* 垂直居中对齐 */
  justify-content: center;     /* 水平居中对齐 */
}

/* 下拉菜单触发器悬停效果 */
.el-dropdown-link:hover {
  color: var(--el-color-primary);  /* 悬停时使用Element Plus的主题色 */
}

/* 抽屉内容区背景色 */
/* :deep() 是 Vue3 的深度选择器，用于修改第三方组件内部样式 */
:deep(.el-drawer__body) {
    background-color: #f5f7fa;
}

/* 抽屉内路由切换动画 */
.slide-fade-enter-active {
  transition: all 0.15s ease-out;    /* 进入过渡 */
  position: absolute;               /* 绝对定位以避免影响布局 */
  width: 100%;                      /* 确保宽度占满容器 */
}

.slide-fade-leave-active {
  transition: all 0.15s ease-in;     /* 离开过渡 */
  position: absolute;               /* 绝对定位以避免影响布局 */
  width: 100%;                      /* 确保宽度占满容器 */
}

.slide-fade-enter-from {
  opacity: 0;                       /* 初始透明 */
  transform: translateX(calc(var(--slide-enter-dict) * 30px));     /* 入 */
}

.slide-fade-leave-to {
  opacity: 0;                       /* 结束时透明 */
  transform: translateX(calc(var(--slide-leave-dict) * 30px));     /* 离开 */
}

/* 抽屉样式调整 */
:deep(.el-drawer__body) {
  background-color: #f5f7fa;
  position: relative;               /* 作为动画定位的参考 */
  overflow: hidden;                 /* 隐藏溢出内容 */
  padding: 20px;                    /* 添加内边距 */
}

/* 优化抽屉打开关闭的动画 */
:deep(.el-drawer) {
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);  /* 平滑的过渡效果 */
}

/* 确保内容容器正确定位 */
:deep(.el-drawer__body > div) {
  position: relative;               /* 相对定位 */
  height: 100%;                     /* 高度占满 */
  width: 100%;                      /* 宽度占满 */
}

:deep(.el-drawer__body) {
  padding: 0;
}

/* 修改卡片容器样式 */
.card-container {
  height: calc(100vh - 120px);
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(195px, 1fr));
  background-color: var(--el-bg-color);
}

.conn-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter);
  width: 190px;
  height: 170px;
  margin: 7px;
  background-color: var(--el-bg-color);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
  position: relative;
}

.conn-card:hover {
  /* transform: translateY(-4px); */
  box-shadow: 0 1px 8px 0 rgba(0, 0, 0, 0.15);  /* 加深阴影 */
  border-color: #0480ec;                        /* 主题色边框 */
}

/* 覆盖 element-plus 卡片默认样式 */
:deep(.el-card__body) {
  padding: 0;
  height: 100%;
}

.card-content {
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 右上角更多按钮样式 */
.card-more {
  position: absolute;
  top: 0px;
  right: 0px;
  padding: 4px;
}

.more-icon {
  font-size: 16px;
  color: var(--el-text-color-placeholder);
  cursor: pointer;
  padding: 6px;
  border-radius: 4px;
}



/* 主要内容样式 */
.card-main {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 上部分 - 图片区域 */
.card-image-section {
  height: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--el-fill-color-lighter);
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.card-logo {
  object-fit: contain;
  filter: grayscale(0.2);
  opacity: 0.9;
}

/* 下部分 - 标题区域 */
.card-title-section {
  padding: 10px;
  align-items: center;
  justify-content: center;
}

.card-title {
  margin: 0;
  font-size: 15px;
  text-align: center;
}

/* 左下角信息图标样式 */
.info-icon {
  position: absolute;
  left: 0px;
  bottom: 0px;
  z-index: 20;
  font-size: 16px;
  color: var(--el-text-color-placeholder);
  background-color: var(--el-bg-color);
  border-radius: 50%;
  padding: 6px;
}



/* 悬浮提示内容样式 */
.tooltip-content {
  padding: 8px;
  font-size: 13px;
  line-height: 1.6;
}

.tooltip-content p {
  margin: 4px 0;
  color: var(--el-text-color-regular);
  display: flex;
  align-items: center;
}

.tooltip-content span {
  color: var(--el-text-color-secondary);
  margin-right: 8px;
  min-width: 70px;
}

/* 下拉菜单项样式 */
:deep(.el-dropdown-menu) {
  min-width: 100px;
  padding: 4px 0;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  padding: 8px 16px;
  height: 36px;
}

:deep(.el-dropdown-menu__item .el-icon) {
  margin-right: 4px;
  font-size: 16px;
}

/* 修改原有的样式以适应新布局 */
.conn-button-container {
  padding: 0 20px;
}

/* 调整图标样式 */
.more-icon {
  font-size: 16px;
  color: var(--el-text-color-placeholder);
  cursor: pointer;
  padding: 6px;
  border-radius: 4px;
}

/* 为 SvgIcon 组件添加样式 */
:deep(.svg-icon) {
  width: 1em;
  height: 1em;
  fill: currentColor;
}
</style>